package top.stmo.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/**
 *          接收消息
 */
public class Consumer_Routing2 {
    public static void main(String[] args) throws IOException, TimeoutException {

        //建立连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置参数
        factory.setHost("106.15.232.23");   //设置ip地址，不设置默认为localhost
        factory.setPort(5672);              //设置端口   默认值为5672
        factory.setVirtualHost("/rooter");  //虚拟机     默认值 /
        factory.setUsername("rooter");      //用户      默认值 guest
        factory.setPassword("rooter");      //密码      默认值 guest
        //创建连接 Connection
        Connection connection = factory.newConnection();
        //创建channel
        Channel channel = connection.createChannel();

        String queueName1 = "test_direct_queue1";
        String queueName2 = "test_direct_queue2";



        //接收消息
        /*
            basicConsume(String queue, boolean autoAck, Consumer callback)
            queue       队列名称
            autoAck     是否自动确认
            callback    回调对象
         */
        Consumer consumer = new DefaultConsumer(channel){
            //回调方法，当收到消息后会自动执行该方法
            /*
                参数：
                    consumerTag         标识
                    envelope            获取一些信息，交换机，路由key...
                    properties          配置信息
                    body                数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                System.out.println("consumerTag：" + consumerTag);
//                System.out.println("Exchange：" + envelope.getExchange());
//                System.out.println("RoutingKey：" + envelope.getRoutingKey());
//                System.out.println("properties：" + properties);
                System.out.println("body：" + new String(body));
                System.out.println("将日志信息打印到控制台");

            }
        };
        channel.basicConsume(queueName2,true,consumer);

        //消费者不用释放资源
    }
}
